package com.woniuxy.subscribe;

import com.rabbitmq.client.Channel;
import com.woniuxy.commen.ConnUtils;
import com.woniuxy.commen.Constansts;

import java.io.IOException;

public class SubConsumer {
    private String name;

    public SubConsumer(String name) {
        this.name = name;
    }

    public void start() throws IOException {
        //建立连接

        //建立信道
        Channel channel = ConnUtils.getconn();

        //创建交换机

        //创建消息队列
        String queueName = channel.queueDeclare().getQueue();

        //绑定交换机
        channel.queueBind(queueName,Constansts.SUB_EXCHANGE,"");

        //接收消息
        /**
         * queue  队列名
         * deliverCallback  收到消息处理
         * cancelCallback   取消消息处理
         */
        try {
            channel.basicConsume(queueName,true,
                    (consumerTag,delivery)->{
                        //处理消息
                        byte[] body = delivery.getBody();
                        String message = new String(body,"utf-8");
                        System.out.println(name+"[x] 收到消息"+message);
                    },(consumerTag)->{});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
